/**
 * Created by litao on 2018/10/25.
 */
import GateWaySocket from '../../socket';
import de from "element-ui/src/locale/lang/de";

export default function (context, router, to, from, next) {
    let whitePermissionCodeList = ['index'],
        $vm = context.$vue.prototype,
        $store = context.$store,
        isLogin = context.utils.objectNotEmp($store.getters.userInfo);

    if(to.meta && to.meta.permissionCode === '*'){
        next();
    }else{
        if(isLogin){
            next();
        }else{
            if($vm.$token.getToken()){
                let maskId = $vm.$openMask(document.body, "资源加载中");
                $vm.$api('user', 'getCurrentUser').then(response => {
                    let userInfo = response.data || {};
                    $store.commit('SAVE_USER', userInfo);

                    //如果重新获取了当前用户，必定要重新加载菜单
                    // $vm.$api('resource', 'queryMyResource').then(response => {
                        // let serverMenus = response.data || [];
                        let serverMenus = require('../http/mock/response/sys/resource/navigate').default || [];

                        if(serverMenus && serverMenus.length > 0){
                            let permissionMenus = $store.getters.menuInfo.permissionMenus || [];
                            let otherMenus = $store.getters.menuInfo.otherMenus || [];

                            if(permissionMenus.length > 0){
                                let permissionMap = {}, indexMap = {};

                                serverMenus.forEach((item, index) => {
                                    permissionMap[item.code] = item;
                                    indexMap[item.code] = index;
                                });

                                let menuMap = {};

                                treeToList(permissionMenus.find(item => item.children && item.children.length > 0).children);

                                function treeToList(source) {
                                    (source || []).forEach(item => {
                                        if(item.name){
                                            menuMap[item.name] = item;

                                            if(item.children && item.children.length > 0){
                                                treeToList(item.children);
                                            }
                                        }
                                    });
                                }

                                permissionMenus[0].children = menuMerge(serverMenus);

                                function menuMerge(source) {
                                    return (source || []).map(item => {
                                        let mapResult = menuMap[item.code];
                                        let result = Object.assign({}, item, mapResult, { children: item.children });

                                        // icon-caidan1

                                        if(mapResult){
                                            result.meta = result.meta || {};
                                            result.meta.icon = item.iconSkin;
                                            result.meta.title = item.name;
                                            if(result.children && result.children.length > 0){
                                                result.children = menuMerge(result.children);
                                            }else{
                                                if(mapResult.children && mapResult.children.length > 0){
                                                    result.children = mapResult.children.filter(cit => cit.meta && (whitePermissionCodeList.includes(cit.meta.permissionCode) || cit.meta.permissionCode === item.code));
                                                }
                                            }

                                            return result;
                                        }
                                    }).filter(item => item);
                                }


                                // let successMenus = handler(permissionMenus, permissionMap);

                                $store.commit('UPDATE_MENU', {
                                    field: 'successMenus',
                                    value: otherMenus.concat(permissionMenus)
                                });

                                router.addRoutes(permissionMenus);
                            }
                        }else{
                            $vm.$error('您没有系统权限！');

                            // setTimeout(() => {
                            //     $vm.$logoutHandler();
                            // }, 500);
                            return;
                        }

                        $store.commit('UPDATE_MENU', {
                            field: 'serverMenus',
                            value: serverMenus
                        });

                        $vm.$closeMask(maskId);

                        next(to.path);
                    });
                // }).catch(error => {
                //     if(error.code === 901){
                //         $vm.$busBroadcast('user-auth-fail');
                //         next('/login');
                //     }
                // });
            }else{
                next('/login');
            }
        }
    }
}
